﻿using System;
using System.Collections.Generic;
using System.Text;
using MySql.Data.MySqlClient;
using OrchardSystemServer.Security;

namespace OrchardSystemServer.Database
{
    public class CommandExecutor
    {
        public bool IsError { set; get; }
        public string LastErrorMessage { set; get; }
        MySQLHelper helper;
        public CommandExecutor()
        {
            helper = new MySQLHelper();
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="user">用户名</param>
        /// <param name="password">密码</param>
        /// <returns>是否登录成功，成功为true</returns>
        public bool UserLogin(string user, string password, ref string token)
        {
            IsError = false;
            string sql = "select count(*) from user where username='" + user + "' and password='" + password + "'";
            try
            {

                if (helper.Count(sql) >= 1)
                {
                    token = UserValidation.GetLoginToken(user, password);
                    if (token.Trim() != "")
                        return true;
                    else
                    {
                        IsError = true;
                        LastErrorMessage = "生成用户登录凭证失败，请稍后再试";
                        return false;
                    }
                }

                else
                {
                    IsError = true;
                    if (helper.IsError)
                    {
                        LastErrorMessage = helper.LastErrorMessage;
                    }
                    else
                    {
                        LastErrorMessage = "用户名或密码错误";
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                IsError = true;
                LastErrorMessage = ex.Message;
                return false;
            }
        }

        /// <summary>
        /// 获得任务编号，此处指果园编号
        /// </summary>
        /// <param name="machineId">机器编号</param>
        /// <param name="orchardId">果园编号</param>
        /// <returns>是否成功</returns>
        public bool GetTask(string machineId, ref string orchardId)
        {
            IsError = false;
            string sql = "select orchardid from orchard where userid in (select userid from device where machineid='" + machineId + "')";
            MySqlDataReader reader = helper.Select(sql);
            Random random = new Random();
            int i = random.Next(reader.FieldCount);//返回一个随机的果园编号,后期可扩展
            int j = 0;
            if (reader.FieldCount == 0)
            {
                IsError = true;
                LastErrorMessage = "该用户暂时还没有果园";
                return false;
            }
            else
            {
                while (reader.Read())
                {
                    if (j == i)
                    {
                        orchardId = reader[0].ToString();
                        break;
                    }
                    else
                        j++;
                }
                if (orchardId.Trim().Equals(""))
                {
                    IsError = true;
                    LastErrorMessage = "该设备没有在系统中注册，请联系管理员注册";
                    return false;
                }

                else
                    return true;
            }
        }

        /// <summary>
        /// 获得果园边界
        /// </summary>
        /// <param name="orchardId">果园编号</param>
        /// <param name="boundary">果边边界</param>
        /// <returns>是否成功</returns>
        public bool GetBoundary(string orchardId, ref string boundary)
        {
            IsError = false;
            StringBuilder sb = new StringBuilder();
            string sql = "select boundaryindex,longitude,latitude from boundary where orchardid=" + orchardId + " order by boundaryindex ASC";
            MySqlDataReader reader = helper.Select(sql);
            while (reader.Read())
            {
                sb.Append(reader["longitude"] + ",");
                sb.Append(reader["latitude"] + "@");
            }
            reader.Close();
            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);//移除最后的'@'号
            boundary = sb.ToString();
            return true;
        }

        /// <summary>
        /// 获得果树信息
        /// </summary>
        /// <param name="orchardId">果园编号</param>
        /// <param name="trees">果树信息</param>
        /// <returns>是否成功</returns>
        public bool GetTrees(string orchardId, ref string trees)
        {
            IsError = false;
            StringBuilder sb = new StringBuilder();
            string sql = "select rfid,longitude,latitude,updatetime from tree where orchardid = " + orchardId;
            MySqlDataReader reader = helper.Select(sql);
            while (reader.Read())
            {
                sb.Append(reader["rfid"] + ",");
                sb.Append(reader["longitude"] + ",");
                sb.Append(reader["latitude"] + ",");
                sb.Append(reader["updatetime"].ToString().Replace('-', '/') + "@");
            }
            reader.Close();
            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);//移除最后的'@'号
            trees = sb.ToString();
            return true;
        }

        /// <summary>
        /// 增加果园边界
        /// </summary>
        /// <param name="orchardId">果园编号</param>
        /// <param name="boundary">果边边界</param>
        /// <returns>是否成功</returns>
        public bool UpdateBoundary(string orchardId, string boundary)
        {
            string sqlDelete = "delete from boundary where orchardid =" + orchardId;//删除之前的边界
            helper.Delete(sqlDelete);
            IsError = false;
            string[] boundayPoint = boundary.Split('@');
            int pointLength = boundayPoint.Length;
            for (int i = 0; i < pointLength; i++)
            {
                string[] strArr = boundayPoint[i].Split(',');
                int boundaryindex = Int32.Parse(strArr[0]);//边界索引
                double longitute = Double.Parse(strArr[1]);//经度
                double latitude = Double.Parse(strArr[2]);//纬度
                string updateTime = strArr[3];//更新时间
                string sql = "insert into boundary values (null," + boundaryindex + "," + orchardId + "," + longitute + "," + latitude + ",'" + updateTime + "')";
                if (helper.Insert(sql) == -1)
                {
                    IsError = true;
                    LastErrorMessage = "增加果园边界失败" + helper.LastErrorMessage;
                    return false;

                }
            }
            return true;
        }

        /// <summary>
        /// 增加果树信息
        /// </summary>
        /// <param name="orchardId">果园编号</param>
        /// <param name="trees">果树信息</param>
        /// <returns>是否成功</returns>
        public bool UpdateTrees(string orchardId, string trees)
        {
            IsError = false;
            string sqlDelete = "delete from tree where orchardid =" + orchardId;//删除之前的果树基本信息
            helper.Delete(sqlDelete);
            string[] treesPoint = trees.Split('@');
            int pointLength = treesPoint.Length;
            for (int i = 0; i < pointLength; i++)
            {
                string[] strArr = treesPoint[i].Split(',');
                int rfid = Int32.Parse(strArr[0]);//rfid
                double longitute = Double.Parse(strArr[1]);//经度
                double latitude = Double.Parse(strArr[2]);//纬度
                string updateTime = strArr[3];//更新时间
                string sql = "insert into tree values (null," + rfid + "," + orchardId + "," + longitute + "," + latitude + ",'" + updateTime + "')";
                if (helper.Insert(sql) == -1)
                {
                    IsError = true;
                    LastErrorMessage += "增加果树" + rfid + "采集信息失败" + helper.LastErrorMessage + ";";

                }
            }
            return !IsError;
        }

        public bool AddTreeCollectInformation(string treesInfo)
        {
            IsError = false;
            string[] infoArr = treesInfo.Split('@');
            int length = infoArr.Length;
            for (int i = 0; i < length; i++)
            {
                string[] arr = infoArr[i].Split(',');
                int rfid = Int32.Parse(arr[0]);//rfid
                double soilTemperature = Double.Parse(arr[1]);//土壤温度
                double soilHumidity = Double.Parse(arr[2]);//土壤湿度
                double airTemperature = Double.Parse(arr[3]);//空气温度
                double airHumidity = Double.Parse(arr[4]);//空气湿度
                string collectTime = arr[5];//采集时间
                string sql = "insert into treeinfo values (null," + rfid + "," + soilTemperature + "," + soilHumidity + "," + airTemperature + "," + soilHumidity + ",'" + collectTime + "')";
                if (helper.Insert(sql) == -1)
                {
                    IsError = true;
                    LastErrorMessage += "增加果树" + rfid + "采集信息失败" + helper.LastErrorMessage + ";";
                }
            }
            return !IsError;
        }

        public int getTreeIdByRfid(int rfid)
        {
            int treeid = -1;//为-1则获得失败
            string sql = "select treeid from tree where rfid=" + rfid;
            MySQLHelper helper = new MySQLHelper();
            MySqlDataReader reader = helper.Select(sql);
            while (reader.Read())
            {
                treeid = Convert.ToInt32(reader[0].ToString());
                break;
            }
            reader.Close();
            return treeid;
        }
    }
}
